from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from random import randint
from libs.yuntongxun.sms import CCP
# import libs.yuntongxun.sms
# Create your views here.


class ImageCodeView(View):
    def get(self, requst, uuid):
        # print(uuid)
        text, image = captcha.generate_captcha()
        # 'code'在配置中的redis定义
        redis_cli = get_redis_connection('code')
        redis_cli.setex(uuid, 100, text)
        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):

    def get(self, request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code, uuid]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)
        if redis_image_code is None:
            return JsonResponse({'code': 400, 'errmsg': '验证码已过期'})
        if redis_image_code != image_code:
            return JsonResponse({'code': 400, 'errmsg': '验证码输入错误'})
        # 提取发送标记
        send_flag = redis_cli.get('send_flag_%S' % mobile)
        if send_flag is not None:
            return JsonResponse({'code': 400, 'errmsg': '不要频繁发送短信'})

        sms_code = '%06d' % randint(0, 999999)
                # 管道 3步
        # ①. 新建一个管道
        pipeline = redis_cli.pipeline()
        # ②. 管道收集指令
        # 5. 保存短信验证码ww
        pipeline.setex(mobile, 300, sms_code)
        # 添加一个发送标记 有效期 60秒 内容是什么都可以
        pipeline.setex('send_flag_%s' % mobile, 60, 1)
        # ③. 管道执行指令
        pipeline.execute()
        # redis_cli.setex(mobile, 300, sms_code)
        # # 添加一个发生标记设置60秒
        # redis_cli.setex('send_flag_%S' % mobile, 60, 1)
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        return JsonResponse({'code': 0, 'errmsg': 'ok'})

        from celery_tasks.sms.tasks import celery_send_sms_code
        # delay参数  等同于 任务（函数）参数
        celery_send_sms_code.delay(mobile, sms_code)
        # 7. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})